package leaveSystem.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import leaveSystem.bizlogic.ViewLeaveManager;
import leaveSystem.model.EmpLeave;
import leaveSystem.model.Employee;

/**
 * Servlet implementation class ApprovalServlet
 */
@WebServlet("/submit")
public class SubmitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SubmitServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProcess(request, response);
	}

	private void doProcess(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		Employee emp=(Employee) session.getAttribute("currentSessionUser");
		int mgrid=emp.getEmployeeId();
		String mgname=emp.getName();
					
		ViewLeaveManager manager=new ViewLeaveManager();
		String comment = request.getParameter("comment");
		String approve = request.getParameter("approve");
		int leaveid =Integer.parseInt( request.getParameter("leaveid"));
		String forward="";
		
		if (approve.equalsIgnoreCase("Rejected") && comment.trim()
				.equalsIgnoreCase("")) {
			
			
			EmpLeave empleave=manager.getEmpLeave(leaveid);
			ArrayList<EmpLeave> leavesonsameperiod=manager.getLeaveOnSamePeriod(empleave, mgrid);
			
			request.setAttribute("empleave", empleave);
			request.setAttribute("mgr","true");
			request.setAttribute("error", "true");
			request.setAttribute("leavesonsameperiod", leavesonsameperiod);
			forward="/CompleteLeaveDetail.jsp";
		}else{
			
			manager.submitDecision(mgname,leaveid, approve, comment);
			//for rd.forward()
			forward="/viewforapproval";
		}

		RequestDispatcher rd = request.getRequestDispatcher(forward);
		rd.forward(request, response);
	}
}
